// ==UserScript==
// @name         预览图助手
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://blogjav.net/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=pixhost.to
// @grant        none


// ==/UserScript==

(function() {
    'use strict';

    // Your code here...
    //alert("blogjav start!");
    let jump = getQueryParam("jump");
    if (jump) {
		findFrstItem();

		findImageUrl();
	}

    insertListItem();



    //#region 自动跳转-长图
    function findFrstItem(){
        // let sreach = document.querySelector('.page-title.ast-archive-title span');
        // let sreachStr = sreach.textContent;

        let sreachStr = getQueryParam("s");
        if (!sreachStr) return;

        let h2Arr = document.querySelectorAll('.entry-title a');
        if (!h2Arr) return;

        let destAaa = null;
        for (let i = 0; i < h2Arr.length; i++) {
            let aaa = h2Arr[i];
            if (i == 5) break;

            // 筛选匹配的番号数据  mium-999 => 正则/mium.*999/gi
            let reg = RegExp(sreachStr, "gi");
            if (reg.test(aaa.innerHTML)) {
                // var fhd_idx = aaa.innerHTML.search(/FHD/i);
                // if (fhd_idx > 0) {
                //     destAaa = aaa;
                //     break;
                // }

                destAaa = aaa;
                break;
            }
        }

        if (destAaa){
            window.location.href = destAaa.href + "?jump=auto";
        }
    }

    function findImageUrl(){
        let imgAaa = document.querySelector('.entry-content a img');

        if (imgAaa) {
            window.location.href = imgAaa.parentElement.href;
        }
    }
    //#endregion

    //#region 工具函数
    function getQueryParam(param) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(param);
    }

    function popupWindow(newUrl, width = 1420, height = 960){
        var left = (window.screen.width - width)/2;
        var top = (window.screen.height - height)/2;
        var popupWindow = window.open(newUrl, '_blank', `left=${left}, top=${top} width=${width}, height=${height}`);
        // popupWindow.location.href = newUrl;
    }

    function getAvCode(str){
        const regex = /[a-zA-Z]{2,5}-\d{2,5}/;
        const match = str.match(regex);
        return match ? match[0] : null;
    }

    function parseJdbUrl(targetUrl){
        let domain = getDomainFromUrl(targetUrl);

        fetch(targetUrl) // 请求用户指定的页面
            .then(response => response.text())
            .then(html => {
                console.log(html);
                const parser = new DOMParser();
                const doc = parser.parseFromString(html, 'text/html');
                const movieList = doc.getElementsByClassName('movie-list');
                if (movieList.length > 0) {
                    const firstElement = movieList[0];
                    const firstLink = firstElement.querySelector('a');
                    if (firstLink) {
                        const href = firstLink.getAttribute('href');

                        var fullUrl = "http://" + domain + href;

                        var newWindow = window.open(fullUrl, '_blank'); // 在新标签页中打开URL
                        // 可选：检查窗口是否成功打开
                        if (!newWindow) {
                            // 窗口可能被浏览器阻止了
                            alert('请允许浏览器打开新窗口或标签页。');
                        }
                    }
                }
            })
            .catch(err => console.error('Error fetching and parsing HTML', err));
    }
    //#endregion

    //#region 列表插入按钮
    function insertListItem(){
        const excerptContainers = document.querySelectorAll('.post-content.ast-width-md-6');

        // 遍历找到的所有元素
        excerptContainers.forEach(container => {
            let titleEle = container.querySelector('.entry-title');
            if(!titleEle){
                return;
            }
            const titleStr = titleEle.innerText;
            const link = container.querySelector('.entry-title a').href;
            // const titleStr = container.innerText;

            const code = getAvCode(titleStr);

            const imgContainer = container.querySelector('.ast-excerpt-container');
            // 创建按钮面板
            const buttonPanel = document.createElement('div');
            buttonPanel.className = 'ast-button-panel';
            buttonPanel.style.cssText = `
                                        display: flex;
                                        gap: 10px;
                                        margin-top: 15px;
                                        padding: 10px;
                                        background-color: #f5f5f5;
                                        border-radius: 5px;
                                        justify-content: flex-end;
                                    `;

            // 转JDB 按钮
            const junmJdbBtn = document.createElement('button');
            junmJdbBtn.textContent = '转JDB';
            junmJdbBtn.style.cssText = `
                                        padding: 8px 16px;
                                        background-color: #007cba;
                                        color: white;
                                        border: none;
                                        border-radius: 3px;
                                        cursor: pointer;
                                        font-size: 14px;
                                    `;
            junmJdbBtn.addEventListener('click', function (){
                if(!code){
                    return;
                }

                // let jdbUrl = "https://javdb458.com/search?q=" + code + "&f=all";
                // parseJdbUrl(jdbUrl);
                let jdbUrl = "https://javdb458.com/search?q=" + code + "&jump=true";
                window.open(jdbUrl, '_blank');
            })

            // 长图 按钮
            const longimgeBtn = document.createElement('button');
            longimgeBtn.textContent = '长图';
            longimgeBtn.style.cssText = `
                                        padding: 8px 16px;
                                        background-color: #7c33ba;
                                        color: white;
                                        border: none;
                                        border-radius: 3px;
                                        cursor: pointer;
                                        font-size: 14px;
                                    `;
            longimgeBtn.addEventListener('click', function (){
                // let imgUrl = "https://blogjav.net/?s=" + code.toLowerCase() + "&jump=auto";
                let imgUrl = link + "?jump=auto";
                popupWindow(imgUrl);
            })

            // 弹窗 按钮
            const infoBtn = document.createElement('button');
            infoBtn.textContent = '弹窗';
            infoBtn.style.cssText = `
                                    padding: 8px 16px;
                                    background-color: #6c757d;
                                    color: white;
                                    border: none;
                                    border-radius: 3px;
                                    cursor: pointer;
                                    font-size: 14px;
                                `;
            infoBtn.addEventListener('click', function (event){
                if(!code){
                    return;
                }
                var newUrl = 'http://localhost:10168/site/premovie/index.html?avcode=' + code.toLowerCase() + '&avtitle=' + titleStr;
                popupWindow(newUrl);
            })


            // 将按钮添加到面板
            buttonPanel.appendChild(junmJdbBtn);
            buttonPanel.appendChild(longimgeBtn);
            buttonPanel.appendChild(infoBtn);

            // 将按钮面板插入到.ast-excerpt-container元素内
            imgContainer.appendChild(buttonPanel);
        });
    }

    //#endregion

})();